<template>
  <!-- 基础地图组件 -->
  <div :id="`map-${idName}`" :style="`height: ${height}`"></div>
</template>
<script setup>
import {onMounted, reactive, ref, watch} from "vue";

const emits = defineEmits(["getMap"]);
const props = defineProps({
  idName: {
    type: String,
    required: true, //必传属性
  },
  height: {
    default: "500px",
  },
});

const state = reactive({
  map: "",
});

const createMap = () => {
  if (document.getElementById(`map-${props.idName}`)) {
    // 创建地图实例
    state.map = new BMap.Map(`map-${props.idName}`, {
      // 地图底图不可点击
      enableMapClick: false,
      enableAutoResize: false,
    });
    setTimeout(() => {
    // 默认成都中心
      state.map.centerAndZoom(new BMap.Point(104.066, 30.663), 14);
    }, 100);

    // 可以使用鼠标缩放地图
    state.map.enableScrollWheelZoom(true);


    // 监听缩放事件，让地图默认移动一下，解决缩放之后某些文字偏移问题
    state.map &&
      state.map.addEventListener("zoomend", (ev) => {
        state.map.panBy(0, 0);
      });
  }
};

watch(()=>state.map,(value, oldValue, onCleanup)=>{
    if(value){
        emits("getMap",value);
    }
})

onMounted(() => {
  createMap();
});
</script>
